<template>
  <!-- 登陆模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="chanisShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <!-- 关闭按钮 -->
      <div class="close" @click="chanisShowLoginModal(false)"></div>
      <!-- 切换导航 -->
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号登陆</a
        >
        |
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode" >微信扫码登录</a>
      </section>
      <!-- 导航对应的内容区域 -->
      <div class="content">
        <!-- 手机号码登录 -->
        <div class="phonelogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入验证码"
              v-model="code"
            />
            <button v-show="!isShowCount" class="btncode" @click="getCode">
              获取验证码
            </button>
            <button v-show="isShowCount" class="btncode">
              {{ `${conut}s` }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 二维码登录 -->
        <div class="qrlogin" v-show="!isShowContent">
          <div id="weixin" class="qrcode">二维码</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { sendSMSAPI, phoneReginAPI,BindPhoneAPI } from "@/request/api";
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      // 手机号码
      phoneNumber: "",
      // 验证码
      code: "",
      // ?秒数
      conut: 5,
      // 是否显示倒计时
      isShowCount: false,
    };
  },
  computed: {
    ...mapState({
      isShowLoginModal: (state) => state.showModal.isShowLoginModal,
      isLogin: (state) => state.loginStatus.isLogin,
      isShowToast: (state) => state.showToast.isShowToast,
      toastMsg: (state) => state.showToast.toastMsg,
      toastType: (state) => state.showToast.toastType,
    }),
  },
  methods: {
    ...mapMutations({
      chanisShowLoginModal: "showModal/chanisShowLoginModal",
      changeIsLogin: "loginStatus/changeIsLogin",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncChangeupdateUserInfo:'userInfo/asyncChangeupdateUserInfo'
    }),
    showQrCode() {
          this.isShowContent = false;
          //获取二维码 并展示
          // 申请微信登录二维码
          let _this = this;
          new WxLogin({
            id: "weixin",
            appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
            scope: "snsapi_login",
            // 扫码成功后重定向的接口
            redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
            // state填写编码后的url
            state: encodeURIComponent(
              window.btoa("http://127.0.0.1:8080" + _this.$route.path)
            ),
            // 调用样式文件
            href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJCb3ggcXJjb2Rlew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9",
          });
        },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 倒计时方法
    Conutdown() {
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.conut--;
        if (this.conut == 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.conut = 59;
        }
      }, 1000);
      // this.isShowCount=true
    },
    // 手机号和验证码方法
    toVerity() {
      // 手机号码验证
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码")
        this.asyncChangeIsShowToast({
          msg: "请输入正确的手机号码",
          type: "danger",
        });
        return false;
      }
      // 滑动验证
      if (!this.msg == "再试一次" || this.msg == "向右滑动") {
        // alert("请先进行滑动验证")
        this.asyncChangeIsShowToast({
          msg: "请进行滑块验证",
          type: "danger",
        });
        return false;
      }
      return true;
    },

    // 手机号码登录 检验验证码
    async getCode() {
      // if(!this.toVerity())return;
      if (!this.toVerity()) return;
      // 获取验证码
      let res = await sendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      console.log("发送结果:", res);
      if (!res) return;
      if (res.code == 0) {
        // alert("发送验证码成功");
        this.asyncChangeIsShowToast({
          msg: "发送验证码成功",
          type: "success",
        });
        this.Conutdown();
      }
    },
    // 登录按钮
    async submitFn() {
      if (!this.toVerity()) return;
      if (this.code.trim() === "") {
        this.asyncChangeIsShowToast({
          msg: "请输入验证码",
          type: "danger",
        });
        return;
      }
      // /发起登录请求
      // 有uuid就表示微信绑定手机号不然就是普通的手机验证登录
      let uuid = localStorage.getItem('uuid')
      let res =null
      if(uuid){
        //绑定手机号
        res = await BindPhoneAPI({
        verifyCode: this.code.trim(),
        phone: this.phoneNumber.trim(),
        uuid:uuid
      });
      }else{
        res = await phoneReginAPI({
        verifyCode: this.code.trim(),
        phone: this.phoneNumber.trim(),
      });
      }
      
      if (!res) return;
      // 提示成功
      alert("登录成功");
      // 保存token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 隐藏模态框
      this.chanisShowLoginModal(false);
      // 登录状态
      this.changeIsLogin(true);
      //删除uuid
      uuid && localStorage.removeItem('uuid');
      //清除地址栏中的code
      this.$router.push(this.$route.path);

      //控制台输出确保这里执行了....
      //登录成功后：获取用户信息
      // let uRes = await UserProfilesAPI();
      // console.log('用户信息：', uRes);
      this.asyncChangeupdateUserInfo();
    },
  },
};
</script>
 
<style lang = "less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    width: 555px;
    height: 423px;
    background: url("../assets/images/login-box-bg.png");
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      width: 22px;
      height: 22px;
      background: url("../assets/images/close.png");
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 50px;
      font-size: 20px;
      a {
        text-decoration: none;
        color: #9b9ab3;
        padding: 0 10px;
        &.active {
          color: #030303;
        }
      }
    }
    .content {
      width: 355px;
      height: 200px;
      margin: 20px auto 0;
      .phonelogin {
        .row {
          display: flex;
          margin-bottom: 20px;
        }
        .ipt {
          outline: none;
          flex: 1;
          height: 48px;
          padding-left: 10px;
        }
        .btn {
          border: none;
          cursor: pointer;
          line-height: 48px;
        }
        .btncode {
          margin-left: 10px;
        }
        .btnlogin {
          color: #fff;
          width: 100%;
          height: 50px;
          background-color: #0a328e;
        }
      }
    }
  }
}

#weixin{
    /* background-color: #fcf; */
    display: flex;
    justify-content: center;
    margin-top: -20px;
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>